package org.shj.sso.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.shj.sso.util.HttpClient;
import org.shj.sso.util.PropertyUtil;

@WebFilter(filterName = "TokenFilter", urlPatterns = "/*")
public class TokenFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpSession session = ((HttpServletRequest)req).getSession();
        HttpServletRequest request = (HttpServletRequest) req;
        Boolean hasLogin = (Boolean)session.getAttribute("isLogin");
        if(hasLogin != null && hasLogin){
        	// 已经登陆了，直接进行后续操作
            System.out.println("已登陆");
            chain.doFilter(req, resp);
            return;
        }
        
        String token = req.getParameter("token");
        
        if(isValidToken(token)){
        	request.getSession().setAttribute("isLogin", true);
        	//String url = request.getRequestURI();
        	//request.getRequestDispatcher(arg0)
        	chain.doFilter(req, resp);
        }else{
        	
        	//如果没有 token，则直接去 SSO 的登陆
            String forward = PropertyUtil.get("sso.login.url");
            String returnUrl = PropertyUtil.get("app.return.url");
            ((HttpServletResponse) resp).sendRedirect(forward + "?returnUrl=" + returnUrl);
        }

    }
    
    private boolean isValidToken(String token){
    	if(token == null || token.isEmpty()){
    		return false;
    	}
    	
    	//TODO 去 SSO 验证 token 是否有效
    	String url = PropertyUtil.get("sso.server.token.check") + "?token=" + token;
    	String result = HttpClient.post(url);
    	if("Valid".equals(result)){
    		return true;
    	}
    	System.out.println("无效的 token");
    	return false;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
